package com.sgb.kjwl.view.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityScanBinding;
import com.swgk.core.takephoto.model.InvokeParam;
import com.im.immodel.IMUtils;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MToast;

import androidx.databinding.DataBindingUtil;

import java.util.List;

import cn.bingoogolapple.qrcode.core.QRCodeView;

@Route(path = "/common/scanActivity")
public class ScanActivity extends AppActivity implements QRCodeView.Delegate {
    private final String TAG = ScanActivity.class.getSimpleName();
    private ActivityScanBinding binding;
    private InvokeParam invokeParam;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ScanActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(ScanActivity.this, R.layout.activity_scan);
        binding.actionBarImageLeft.setOnClickListener(View -> finish());
        binding.actionBarTitle.setText("二维码");
        binding.ivPhotoAlbum.setVisibility(View.VISIBLE);
        binding.ivPhotoAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onJumpPictures();
            }
        });
        binding.zxingview.setDelegate(this);
        binding.openFlashlight.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                binding.lightTitle.setText("轻触关闭");
                binding.zxingview.openFlashlight();
            } else {
                binding.lightTitle.setText("轻触照亮");
                binding.zxingview.closeFlashlight();
            }
        });
    }

    @Override
    protected void init() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        binding.zxingview.startCamera();
        binding.zxingview.startSpotAndShowRect();
    }

    @Override
    protected void onStop() {
        binding.zxingview.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        binding.zxingview.onDestroy();
        super.onDestroy();
    }

    @SuppressLint("MissingPermission")
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        LogUtil.d(TAG, "result: " + result);
        vibrate();
//        binding.zxingview.startSpot();
        if (TextUtils.isEmpty(result)) {
            MToast.showToast(ScanActivity.this, "没有识别到二维码信息");
            return;
        }

        if (result.startsWith("qrcode")) {
            String replace = result.replace("qrcode:", "");
            ScanLoginActivity.start(ScanActivity.this, replace);
            //binding.actionBarTitle.setText(result);
        } else if (result.startsWith("friend")) {
            //binding.actionBarTitle.setText(result);
            IMUtils.getInstance().startEmployeeCard(result);
        } else if (result.startsWith("group")) {
            binding.actionBarTitle.setText("加入群聊");
        } else if (result.startsWith("qrCompany:")) {
            binding.actionBarTitle.setText("加盟企业");
        } else if (result.startsWith("invite")) {
        } else if (result.startsWith("AddGroup")) {
            IMUtils.getInstance().startGroupApply(result);
        } else {
            WebViewX5HostActivity.start(ScanActivity.this, result);
        }
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        String tipText = binding.zxingview.getScanBoxView().getTipText();
        String ambientBrightnessTip = "环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                binding.zxingview.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                binding.zxingview.getScanBoxView().setTipText(tipText);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        LogUtil.e(TAG, "打开相机出错");
    }

    private void onJumpPictures() {
        boolean hasPermission = EsayPermissions.isHasPermission(ScanActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (hasPermission) {
            Intent innerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
            startActivityForResult(wrapperIntent, 10);
        } else {
            EsayPermissions.with(ScanActivity.this).permission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    Intent innerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
                    startActivityForResult(wrapperIntent, 10);
                    return;
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {
                    MToast.showToast(ScanActivity.this, "存储权限未开启");
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            if (data != null) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                binding.zxingview.decodeQRCode(picturePath);
            }
        }
    }
}